<template>
  <a-form class="json-schema-form">
    <RowsView v-if="formState.show" @value-change="handleValueChange" :schemas="schemas" />
  </a-form>
</template>
<script setup lang="ts">
import { getProp } from '@cms/utils'
import { onMounted } from 'vue'
import RowsView from './RowsView'
import type { JsonChangeValue, JsonSchema } from './types'
import { debugRun } from '@cms/utils'
import { formState } from './mixins/useState'
import { cloneDeep } from 'lodash-unified'

interface JsonSchemaFormProps {
  debug?: boolean
  schemas: JsonSchema[]
  model: any
}

const props = withDefaults(defineProps<JsonSchemaFormProps>(), { debug: false })
const handleValueChange = (changeValue: JsonChangeValue) => {
  debugRun(
    () => {
      console.log(
        JSON.stringify({
          title: '数据变更',
          ...changeValue
        })
      )
    },
    { debug: formState.debug }
  )
  getProp(formState.model, changeValue.path).value = changeValue.value
}
onMounted(() => {
  formState.debug = props.debug
  formState.model = props.model
  formState.sourceModel = cloneDeep(props.model)
  formState.show = true
})
</script>
